using System;
using System.Collections.Generic;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.Globalization;

namespace Advertisement
{
  public enum GameTitle
  {
    Crossroads,
    Dice3D,
    EbookReader,
    Eleven,
    Enigma,
    Flashlight,
    RisikoDice,
    Ideopuzzle,
    Scopa,
    SpaceBattle,
  }

  public class AdsComponent : DrawableGameComponent
  {
    private List<GameTitle> game_to_ad;
    private List<GameTitle> game_add;
    private Texture2D bg;
    private List<Texture2D> games_tile;
    private List<Vector2> tiles_position;
    private Vector2 bg_pos, fr_s, sn_s;
    private SpriteBatch spriteBatch;
    private SpriteFont font;

    private float time_before_exit, elapsed_time, bg_rot;

    public AdsComponent(Game game, List<GameTitle> game_to_ad, float time_before_exit)
      : base(game)
    {
      this.time_before_exit = time_before_exit;
      this.game_to_ad = game_to_ad;

      Resources.Strings.Culture = CultureInfo.CurrentCulture;

      TouchPanel.EnabledGestures = GestureType.Tap;
    }

    public override void Initialize()
    {
      elapsed_time = time_before_exit;
      bg_rot = 0;

      base.Initialize();
    }

    protected override void LoadContent()
    {
      spriteBatch = new SpriteBatch(Game.GraphicsDevice);

      var isLandscape = Game.GraphicsDevice.Viewport.Width > Game.GraphicsDevice.Viewport.Height ? true : false;
      var random = new Random(DateTime.Now.Millisecond);

      games_tile = new List<Texture2D>();
      tiles_position = new List<Vector2>();
      game_add = new List<GameTitle>();

      var n = Math.Min(5, game_to_ad.Count);

      for (int i = 1; i <= n; i++)
      {
        var ind = random.Next(game_to_ad.Count);

        games_tile.Add(GetGameTile(game_to_ad[ind]));
        tiles_position.Add(GetTilePosition(i));

        game_add.Add(game_to_ad[ind]);
        game_to_ad.RemoveAt(ind);
      }

      bg = Game.Content.Load<Texture2D>("../AdvertisementContent/Shared/ads_bg");
      font = Game.Content.Load<SpriteFont>("../AdvertisementContent/Fonts/Regular30");

      if (isLandscape)
      {
        bg_pos = Vector2.Zero;

        fr_s = new Vector2(190 - font.MeasureString(Resources.Strings.First_S).X / 2.0f, 60);
        sn_s = new Vector2(190 - font.MeasureString(Resources.Strings.Second_S).X / 2.0f, 110);
      }
      else
      {
        bg_rot = MathHelper.ToRadians(90);
        bg_pos = new Vector2(bg.Height, 0);

        fr_s = new Vector2(130 - font.MeasureString(Resources.Strings.First_S).X / 2.0f, 90);
        sn_s = new Vector2(130 - font.MeasureString(Resources.Strings.Second_S).X / 2.0f, 135);
      }

      base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {
      elapsed_time -= (float)gameTime.ElapsedGameTime.TotalSeconds;

      if (elapsed_time <= 0)
        Game.Exit();

      if (TouchPanel.IsGestureAvailable)
      {
        GestureSample gesture = TouchPanel.ReadGesture();
        Point gesturePoint = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
        
        // TAP
        if (gesture.GestureType.Equals(GestureType.Tap))
        {
          for (int i = 0; i < games_tile.Count; i++)
          {
            Rectangle TileRect = new Rectangle((int)tiles_position[i].X, (int)tiles_position[i].Y, games_tile[i].Bounds.Width, games_tile[i].Bounds.Height);

            if (TileRect.Contains(gesturePoint)) // Tile Tapped
            {
              MarketplaceDetailTask detailTask = new MarketplaceDetailTask();
              detailTask.ContentIdentifier = GetProductID(game_add[i]);
              detailTask.Show();
            }
          }
        }
      }

      base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
      spriteBatch.Begin();

      spriteBatch.Draw(bg, bg_pos, null, Color.White, bg_rot, Vector2.Zero, 1, SpriteEffects.None, 0);

      for (int i = 0; i < games_tile.Count; i++)
        spriteBatch.Draw(games_tile[i], tiles_position[i], Color.White);

      spriteBatch.DrawString(font, Resources.Strings.First_S, fr_s, Color.White);
      spriteBatch.DrawString(font, Resources.Strings.Second_S, sn_s, Color.White);

      spriteBatch.End();

      base.Draw(gameTime);
    }

    private Texture2D GetGameTile(GameTitle g)
    {
      return Game.Content.Load<Texture2D>("../AdvertisementContent/GameTiles/" + g.ToString());
    }

    private string GetProductID(GameTitle g)
    {
      string productID = ProductIDList.Scopa;

      if (g == GameTitle.Crossroads) productID = ProductIDList.Crossroads;
      if (g == GameTitle.Dice3D) productID = ProductIDList.Dice3D;
      if (g == GameTitle.EbookReader) productID = ProductIDList.EbookReader;
      if (g == GameTitle.Eleven) productID = ProductIDList.Eleven;
      if (g == GameTitle.Enigma) productID = ProductIDList.Enigma;
      if (g == GameTitle.Flashlight) productID = ProductIDList.FlashlightDeluxe;
      if (g == GameTitle.Ideopuzzle) productID = ProductIDList.Ideopuzzle;
      if (g == GameTitle.RisikoDice) productID = ProductIDList.FreeRiskDice;
      if (g == GameTitle.Scopa) productID = ProductIDList.Scopa;
      if (g == GameTitle.SpaceBattle) productID = ProductIDList.SpaceBattle;

      return productID;
    }

    private Vector2 GetTilePosition(int i)
    {
      var isLandscape = Game.GraphicsDevice.Viewport.Width > Game.GraphicsDevice.Viewport.Height ? true : false;

      if (isLandscape)
      {
        switch (i)
        {
          case 1:
            return new Vector2(330, 16);
          case 2:
            return new Vector2(536, 16);
          case 3:
            return new Vector2(102, 243);
          case 4:
            return new Vector2(330, 243);
          default:
            return new Vector2(536, 243);
        }
      }
      else
      {
        switch (i)
        {
          case 1:
            return new Vector2(256, 31);
          case 2:
            return new Vector2(48, 276);
          case 3:
            return new Vector2(256, 276);
          case 4:
            return new Vector2(48, 542);
          default:
            return new Vector2(256, 542);
        }
      }
    }
  }
}
